import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Input, Card, Select, message, Popover } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryInvoiceListParams, Invoice } from './services';
import { InvoiceStatus, InvoiceTitleType, queryInvoiceList, reMakeInvoice } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { Access, history } from '@umijs/max'
import InvoiceStatusHook from './Status'
import { jump2target } from '@/utils/common';

const InvoicePage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryInvoiceListParams>()
  const [searchParams, setSearchParams] = useState<QueryInvoiceListParams>({
    pageNum: 1, pageSize: 10,
  })
  const list = useRequest(() => queryInvoiceList(searchParams), {
    refreshDeps: [searchParams],
  })
  const reOpen = useRequest(reMakeInvoice, {manual: true})

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      status: formValues.status,
      orderType: formValues.orderType,
      telephone: formValues.telephone,
      pageNum: 1,
    })
  }

  const openDetail = (record: Invoice) => {
    sessionStorage.setItem(record.recordId, JSON.stringify(record))
    jump2target(`/moneySettle/invoice/detail?sKey=${record.recordId}___${new Date().getTime()}`, {needRefresh: true})
  }

  const reMake = (record: Invoice) => {
    reOpen.runAsync({invoiceId: record.recordId})
    .then(() => {
      message.success('请求成功')
      list.refresh()
    })
  }

  const downPdf = (record: Invoice) => {
    window.open(record.pdfUrl, '_blank')
  }

  const columns: ColumnsType<Invoice> = [
    {
      title: '订单类型',
      dataIndex: 'orderType',
      width: 160,
      render: orderType => {
        if (orderType === 1) return '占位费'
        if (orderType === 2) return '充电订单费'
        return '--'
      }
    },
    {
      title: '抬头人',
      dataIndex: 'infoName',
      width: 160,
    },
    {
      title: '抬头类型',
      dataIndex: 'infoType',
      width: 120,
      render: val => InvoiceTitleType[val],
    },
    {
      title: '抬头手机号',
      dataIndex: 'telephone',
      width: 120,
    },
    {
      title: '用户手机号',
      dataIndex: 'userPhone',
      width: 120,
      render: val => val || '--'
    },
    {
      title: '电费金额(元)',
      dataIndex: 'electricMoney',
      width: 120,
      render: val => val?.toLocaleString(),
    },
    {
      title: '服务费金额(元)',
      dataIndex: 'serviceMoney',
      width: 140,
      render: val => val?.toLocaleString(),
    },
    {
      title: '总金额(元)',
      dataIndex: 'totalMoney',
      width: 140,
      render: val => val?.toLocaleString(),
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      width: 140,
      render: val => dayjs(val).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '发票状态',
      dataIndex: 'status',
      width: 140,
      render: (val, record) => {
        if (val === InvoiceStatus.开票失败) {
          return <div>
            <div>{InvoiceStatus[val]}</div>
            {record.reason ? <div>
              <Popover content={record.reason}>失败原因: {record.reason}</Popover>
            </div> : ''}
          </div>
        }
        return InvoiceStatus[val]
      },
    },
    {
      title: '操作',
      key: 'operation',
      width: 160,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <a onClick={() => openDetail(record)}>发票详情</a>
          <Access accessible={record.status === InvoiceStatus.开票失败}>
            <a onClick={() => reMake(record)}>重开发票</a>
          </Access>
          <Access accessible={record.status === InvoiceStatus.开票成功}>
            <a onClick={() => downPdf(record)}>下载发票</a>
          </Access>
        </Space>
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshInvoiceList', refresh)
    return () => {
      window.removeEventListener('refreshInvoiceList', refresh)
    }
  }, [])

  return (
    <div className='container'>
      <InvoiceStatusHook />
      <Card>
        <div className="search-card">
          <Form name='searchInvoiceForm' form={searchForm} onFinish={onFinish} initialValues={{
            timeRange: [dayjs().subtract(30, 'days'), dayjs()]
          }}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='用户手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选中' options={[
                    {label: '待开票', value: InvoiceStatus.待开票},
                    {label: '开票成功', value: InvoiceStatus.开票成功},
                    {label: '开票失败', value: InvoiceStatus.开票失败},
                    {label: '开票中', value: InvoiceStatus.开票中},
                  ]} style={{width: '100%'}} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='订单类型' name='orderType'>
                  <Select placeholder='请选中' options={[
                    {label: '占位费', value: 1},
                    {label: '充电订单费', value: 2},
                  ]} style={{width: '100%'}} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </Card>
      <Card>
        <Table<Invoice>
          rowKey='recordId'
          loading={list.loading || reOpen.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </Card>
    </div>
  );
};

export default InvoicePage;
